package com.example.xgakj.newterminal.pushmodule;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.example.xgakj.mylibrary.mvp.utils.ByteUtil;
import com.example.xgakj.mylibrary.mvp.utils.SharedPreferencesUtil;
import com.example.xgakj.newterminal.R;
import com.example.xgakj.newterminal.base.BaseApplication;
import com.example.xgakj.newterminal.base.Parameters;
import com.example.xgakj.newterminal.beans.AlarmInfoBean;
import com.example.xgakj.newterminal.models.BaseJsonCallBack;
import com.example.xgakj.newterminal.models.QueryModel;
import com.socks.library.KLog;

import org.ddpush.im.v1.client.appuser.Message;
import org.ddpush.im.v1.client.appuser.TCPClientBase;

import java.util.ArrayList;


public class OnlineService extends Service {
    // 动态注册锁屏等广播
    private ScreenReceiverUtil mScreenListener;
    // 1像素Activity管理类
    private ScreenManager mScreenManager;
    private ScreenReceiverUtil.SreenStateListener mScreenListenerer = new ScreenReceiverUtil.SreenStateListener() {
        @Override
        public void onSreenOn() {
            // 移除"1像素"
            mScreenManager.finishActivity();
        }


        @Override
        public void onSreenOff() {
            // 接到锁屏广播，将SportsActivity切换到可见模式
            // "咕咚"、"乐动力"、"悦动圈"就是这么做滴
//            Intent intent = new Intent(SportsActivity.this,SportsActivity.class);
//            startActivity(intent);
            // 如果你觉得，直接跳出SportActivity很不爽
            // 那么，我们就制造个"1像素"惨案
            mScreenManager.startActivity();
        }


        @Override
        public void onUserPresent() {
            // 解锁，暂不用，保留
        }
    };

    protected PendingIntent tickPendIntent;
    WakeLock wakeLock;
    MyTcpClient myTcpClient;

    public class MyTcpClient extends TCPClientBase {

        public MyTcpClient(byte[] uuid, int appid, String serverAddr, int serverPort)
                throws Exception {
            super(uuid, appid, serverAddr, serverPort, 10);

        }

        @Override
        public boolean hasNetworkConnection() {
            return Util2.hasNetwork(OnlineService.this);

        }


        @Override
        public void trySystemSleep() {
            tryReleaseWakeLock();
        }

        @Override
        public void onPushMessage(Message message) {
            if (message == null) {
                return;
            }
            if (message.getData() == null || message.getData().length == 0) {
                return;
            }
            KLog.e("收到推送");
            String content = null;
            try {
                content = new String(message.getData(), 5, message.getContentLength(), "UTF-16LE");
                KLog.e(content);
//				 content = new String(msg.getData(), 5, msg.getContentLength(), "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (SharedPreferencesUtil.getBoolean(OnlineService.this, Parameters.ALARM_NOTICE, true)) {
                openAlarmInfo(content);

            }

        }

    }

    private void openAlarmInfo(String content) {

        KLog.i("content: " + content);
        int n = content.indexOf("[");
        int n2 = content.indexOf("]");
        int n3 = content.indexOf("->");
        String receiver_date = content.substring(0, n);//警情时间
        String customer_id = content.substring(n + 1, n2);//客户ID
        String alarm_content = content.substring(n2 + 1, n3);//警情内容
        String table_id = content.substring(n3 + 2);//警情表ID
        if (table_id == null) {
            return;
        }
        String field = "id,CustID,custname,JQNeiRong,dev_id,cust_ip,ChengquID,DateOn,Fangqu,ClientOK,Partid,updateTime,updateTime2,disposal,ifok,SendOk,itype,Note,Address,partname";
        String param = "id=" + "'" + table_id + "'";
        queryAlarmInfo(field, param);

    }

    private void queryAlarmInfo(String field, String param) {

        QueryModel.getInstance().queryAlarmInfo(field,param, new BaseJsonCallBack<ArrayList<AlarmInfoBean>>(null) {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<ArrayList<AlarmInfoBean>> response) {
                ArrayList<AlarmInfoBean> list = response.body();
                if (list != null && list.size() > 0) {
                    AlarmInfoBean infoBean = list.get(0);
                    KLog.e(infoBean.toString());
                    Intent msIntent = new Intent(OnlineService.this, MessageActivity.class);
                    msIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    msIntent.putExtra(Parameters.VIEW_YUYINALARMLOGS, infoBean);
                    startActivity(msIntent);
                }
            }
        });

    }


    public OnlineService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "OnlineService");

//        resetClient();

            Log.d("shurun", "--->onCreatefuwy");

        // 1. 注册锁屏广播监听器
        mScreenListener = new ScreenReceiverUtil(this);
        mScreenManager = ScreenManager.getScreenManagerInstance(this);
        mScreenListener.setScreenReceiverListener(mScreenListenerer);
    }

    @Override
    public int onStartCommand(Intent param, int flags, int startId) {
        if (param == null) {
            return START_STICKY;
        }
        String cmd = param.getStringExtra("CMD");
        if (cmd == null) {
            cmd = "";
        }
        if (cmd.equals("TICK")) {
            if (wakeLock != null && wakeLock.isHeld() == false) {
                wakeLock.acquire();
            }
        }
        if (cmd.equals("RESET")) {
            if (wakeLock != null && wakeLock.isHeld() == false) {
                wakeLock.acquire();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    resetClient();
                }
            }).start();

        }
        if (cmd.equals("TOAST")) {
            String text = param.getStringExtra("TEXT");
            if (text != null && text.trim().length() != 0) {
                Toast.makeText(this, text, Toast.LENGTH_LONG).show();
            }
        }

        notifyRunning();
        return START_STICKY;
    }


    protected void resetClient() {

        String serverIp = SharedPreferencesUtil.getString(OnlineService.this,Parameters.SERVER_IP,"120.25.205.244") ;
        String serverPort = SharedPreferencesUtil.getString(OnlineService.this,Parameters.SERVER_PORT,"9966") ;
        String pushPort = SharedPreferencesUtil.getString(OnlineService.this,Parameters.PUSH_PORT,"9999") ;
        String userName = BaseApplication.usrID;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 26; i++) {
            stringBuilder.append("0");
        }
        String uuid = stringBuilder.append(userName).toString();
        KLog.e("UUID:" + uuid);
        if (serverIp == null || serverIp.trim().length() == 0
                || serverPort == null || serverPort.trim().length() == 0
                || pushPort == null || pushPort.trim().length() == 0
                || userName == null || userName.trim().length() == 0) {
            return;
        }
        if (this.myTcpClient != null) {
            try {
                myTcpClient.stop();
            } catch (Exception e) {
            }
        }
        byte[] bytes = ByteUtil.hexStringToBytes2(uuid);
        try {
            myTcpClient = new MyTcpClient(bytes, 1, serverIp, Integer.parseInt(serverPort));
            myTcpClient.setHeartbeatInterval(50);
            myTcpClient.start();
        } catch (Exception e) {
            Toast.makeText(this.getApplicationContext(), "操作失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
//        Toast.makeText(this.getApplicationContext(), "ddpush：终端重置", Toast.LENGTH_LONG).show();
    }

    protected void tryReleaseWakeLock() {
        if (wakeLock != null && wakeLock.isHeld() == true) {
            wakeLock.release();
        }
    }


    protected void notifyRunning() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setAutoCancel(false)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.icon1)
                .setTicker("接警服务正在运行")
                .setContentTitle("用户接警")
                .setContentText("正在运行")
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
//				.setContentIntent(pi)
                .setAutoCancel(true)
                .setContentInfo("信息");
        Notification notify = builder.build();
        startForeground(1, notify);
    }

    protected void cancelNotifyRunning() {
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(1);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelNotifyRunning();
        mScreenListener.stopScreenReceiverListener();
        tryReleaseWakeLock();
        if (myTcpClient != null) {
            try {
                myTcpClient.stop();
            } catch (Exception e) {
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


}
